package com.jt.permission.controller;

import com.jt.base.utils.PageUtil;
import com.jt.base.utils.R;
import com.jt.permission.helper.TransactionalHelper;
import com.jt.permission.model.Role;
import com.jt.permission.service.RoleService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author longheping
 * @date 2018/6/21 15:44
 */
@RestController
@RequestMapping("admin/sys/role")
@Validated
public class RoleController {
    private static final Logger logger = LoggerFactory.getLogger(RoleController.class);
    @Resource
    private RoleService roleService;
    @Resource
    private TransactionalHelper transactionalHelper;

    @RequestMapping("/search")
    public R search(
            @Valid @Min(value = 0, message = "页码不能小于0") int page,
            @Valid @Max(value = 1000, message = "请求数量最大不能超过1000") int limit,
            @RequestParam(value = "roleId", required = false) Long roleId,
            @RequestParam(value = "roleName", required = false) String roleName
    ) {
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(roleName)) {
            criteria.andLike("roleName", "%" + roleName + "%");
        }
        if (roleId != null) {
            criteria.andEqualTo("roleId", roleId);
        }
        List<Role> list = roleService.selectListByExample(example, page, limit);
        return PageUtil.wrap(new PageInfo<>(list), R.ok());
    }


    /**
     * 保存用户
     */
    @RequestMapping("/save")
    public R save(@RequestBody JSONObject jb) {
        Role role = JSONObject.toJavaObject(jb, Role.class);
        String menuIds = jb.getString("menuIds");
        Example example = new Example(Role.class);
        example.createCriteria().andEqualTo("roleName", role.getRoleName());
        List<Role> sysRoleList = roleService.selectListByExample(example);
        if (sysRoleList != null && sysRoleList.size() > 0) {
            if (!sysRoleList.get(0).getRoleId().equals(role.getRoleId())) {
                return R.error("角色名已经存在");
            }
        }
        List<Long> menuIdList = new ArrayList<>();
        List<String> idStrList = Arrays.asList(menuIds.split(","));
        idStrList.forEach(s -> {
            if (StringUtils.isNumeric(s)) {
                menuIdList.add(Long.parseLong(s));
            }
        });
        transactionalHelper.saveOrUpdateRoleMenu(role, menuIdList);
        return R.ok();
    }

    /**
     * 获取所有角色附带用户角色信息
     *
     * @param userId
     * @return
     */
    @RequestMapping("/getRoleWithUserRoleInfo")
    public R getRoleWithUserRoleInfo(@RequestParam(required = false, defaultValue = "0") Long userId) {
        List<Role> sysRoleList = roleService.selectAll();//获取所有角色，便于在后面选择权限
        if (userId > 0) {
            List<Role> sysRoles = roleService.queryAllRolles(userId);//获取用户拥有的角色
            sysRoleList.stream().forEach(sysRole ->                //遍历两个list，选出用户拥有的角色
                    sysRoles.stream().forEach(s -> {
                        if (s.getRoleId().equals(sysRole.getRoleId())) {
                            sysRole.setHasOwn(1);
                        }
                    })
            );
        }
        return PageUtil.wrap(new PageInfo<>(sysRoleList), R.ok());
    }

    @RequestMapping("/get/{id}")
    public R get(@PathVariable String id) {
        return R.ok();
    }


    @RequestMapping("/delete")
    public R delete(@RequestParam("ids") String ids) {

        return R.ok();
    }

}
